package com.cameron.serviceedu.controller.front;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cameron.serviceedu.entity.EduCourse;
import com.cameron.entity.EduTeacher;
import com.cameron.serviceedu.service.EduCourseService;
import com.cameron.serviceedu.service.EduTeacherService;
import com.cameron.utils.Result;
import com.hooper.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@SuppressWarnings("unchecked")
@RestController
@CrossOrigin
@Slf4j
@RequestMapping("service/index-front")
public class IndexController {

    @Resource
    private EduTeacherService teacherService;

    @Resource
    private EduCourseService courseService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("index")
    public Result index() {

        String courseKey = "edu:course:hot";

        List<EduCourse> courseList = (List<EduCourse>) redisTemplate.opsForValue().get(courseKey);
        if (CollectionUtils.isEmpty(courseList)) {
            //查询前8条热门课程
            LambdaQueryWrapper<EduCourse> wrapper = new LambdaQueryWrapper<>();
            wrapper.orderByDesc(EduCourse::getViewCount)
                    .last("limit 4");

            courseList = courseService.list(wrapper);
            redisTemplate.opsForValue().set(courseKey, courseList, RandomUtil.randomInt(10000, 200000), TimeUnit.MILLISECONDS);
        }

        String teacherKey = "edu:teacher:hot";

        List<EduTeacher> teacherList = (List<EduTeacher>) redisTemplate.opsForValue().get(teacherKey);
        if (CollectionUtils.isEmpty(teacherList)) {
            //查询前4名讲师
            LambdaQueryWrapper<EduTeacher> lqw = new LambdaQueryWrapper<>();
            lqw.orderByDesc(EduTeacher::getLevel)
                    .last("limit 4");
            teacherList = teacherService.list(lqw);
            redisTemplate.opsForValue().set(teacherKey, teacherList, RandomUtil.randomInt(10000, 200000), TimeUnit.MILLISECONDS);
        }
        return Result.ok().data("courseList", courseList).data("teacherList", teacherList);
    }
}
